//
//  GRGoodDetailPageVC.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/8/27.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRGoodDetailPageVC.h"
#import "GRDetailFootSectionView.h"
#import "GRGoodDetailContentCell.h"
#import "GRGoodCountTableViewCell.h"
#import "GRBuyMsgTableViewCell.h"
#import "GRGoodDetailAlbumView.h"
#import "GRDetailPageStoreCelll.h"
#import "GRSotreCommentTableViewCell.h"
#import "GRStoreSectionHeaderView.h"
#import "GRDetailFootSectionView.h"
#import "GRStoreSectionFooterView.h"
#import "GRSubmitOrderVC.h"
#import "GRStoreAction.h"
#import "GRGoodDetailPageModel.h"
#import "GRShowMoreListVC.h"
#import "GRStoreViewController.h"
#import "GRBarginViewController.h"
#import "GRhaggleModel.h"
#import "GRGoodWebHtmlCell.h"
@interface GRGoodDetailPageVC ()<UITableViewDataSource,UITableViewDelegate,GRGoodDetailAlbumViewDelegate,GRStoreSectionFooterViewDelegate,GRGoodWebHtmlCellDelegate>
{
    CGFloat webHeight;
    
}
@property (weak, nonatomic) IBOutlet UITableView *goodList;
@property(nonatomic,strong)GRGoodDetailAlbumView * albumView;
@property(nonatomic,strong)GRGoodDetailPageModel * detailPageModel;
@property (weak, nonatomic) IBOutlet UIButton *collectionBt;
@property (weak, nonatomic) IBOutlet UIButton *bottomBt;
@property(nonatomic,strong)NSTimer *timer;

@end

@implementation GRGoodDetailPageVC
-(NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changCouponsState) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    return _timer;
}

-(void)changCouponsState{
    
    
    [self.bottomBt setTitle:[NSString stringWithFormat:@"距离砍价结束仅剩%@\n继续砍价",[self getTimeStr:self.detailPageModel.expiresIn]] forState:UIControlStateNormal];
    self.bottomBt.titleLabel.numberOfLines = 0;
    self.bottomBt.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.detailPageModel.expiresIn--;
}


-(NSString *)getTimeStr:(long long)timeStamp{
    NSString *time;
    if (timeStamp < 0) {
        time = @"0";
    }else{
        int day = (int)(timeStamp / (3600 * 24));
        int hour = (int)((timeStamp - day * 3600 * 24) / 3600);
        int minute = (int)(timeStamp - day * 3600 * 24 - hour * 3600) / 60;
        int second = (int)(timeStamp - day * 3600 * 24 - hour * 3600 - minute * 60);
        
        if (day <= 0&& hour > 0) {
            if (hour <= 0 && minute > 0) {
                time = [NSString stringWithFormat:@"%02d:%02d",minute, second];
                
            }else if (minute <= 0 && hour <= 0){
                
                if (second >= 10) {
                    time = [NSString stringWithFormat:@"%02d",second];
                }else {
                    time = [NSString stringWithFormat:@"%01d",second];
                }
                
            }else{
                
                time = [NSString stringWithFormat:@"%02d:%02d:%02d",hour, minute, second];
            }
        }else{
            time = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d",day,hour,minute,second];
        }
    }
    return time;
}

-(GRGoodDetailAlbumView *)albumView{
    if (!_albumView) {
        _albumView = [GRGoodDetailAlbumView xx_instantiateFromNib];
        _albumView.frame = CGRectMake(0, 0, KscreenWidth, KscreenWidth *16/15);
        _albumView.delegate = self;
    }
    return _albumView;
}

- (void)scrollImageCurrentIndex:(NSInteger)index{
    
}

-(void)seleteImageIndex:(NSInteger)index imagArr:(NSArray*)imageArr{
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    WEAKSELF
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = (id)weakSelf;
    }
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.goodList registerNib:[UINib nibWithNibName:@"GRGoodDetailContentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"contentCell"];
    [self.goodList registerNib:[UINib nibWithNibName:@"GRGoodCountTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"countCell"];
    [self.goodList registerNib:[UINib nibWithNibName:@"GRBuyMsgTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BuyMsgCell"];
    [self.goodList registerNib:[UINib nibWithNibName:@"GRDetailPageStoreCelll" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"storeCell"];
    [self.goodList registerNib:[UINib nibWithNibName:@"GRSotreCommentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commentCell"];
    [self.goodList registerNib:[UINib nibWithNibName:@"GRGoodWebHtmlCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"webCell"];
    self.goodList.tableHeaderView = self.albumView;
    if (@available(iOS 11.0, *)) {
        self.goodList.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    if (_isBargain) {
        [self.bottomBt setTitle:@"我要砍价免费拿" forState:UIControlStateNormal];
        self.bottomBt.backgroundColor = HEXCOLOR(0xFF331F);
        [self.bottomBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }else{
        [self.bottomBt setTitle:@"立即购买" forState:UIControlStateNormal];
        self.bottomBt.backgroundColor = HEXCOLOR(0xFBD62D);
        [self.bottomBt setTitleColor:HEXCOLOR(0x222222) forState:UIControlStateNormal];
    }
    [self requestData];
}

-(void)requestData{
       CLLocationCoordinate2D location =  [GRLocationManager defaultManager].coordinate;
    NSDictionary * dic = @{
                           @"lantitude":@(location.latitude),
                           @"longitude":@(location.longitude),
                           @"profileId":[GRUserBasisInfo BasisID]?[GRUserBasisInfo BasisID]:@""
                           };
    [GRStoreAction getGoodDetailPageWithGoodId:self.goodId ParamerDic:dic  IsBargain:_isBargain  ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        if (success) {
           
            NSLog(@"%@",responseObject);
            self.detailPageModel = [GRGoodDetailPageModel yy_modelWithDictionary:responseObject];
            if (self.detailPageModel.status&&self.detailPageModel.expiresIn != 0) {
                [self.timer setFireDate:[NSDate distantPast]];
            }
            [self.collectionBt setImage:[UIImage imageNamed:  self.detailPageModel.isFavorite?@"alreadyCollect": @"notCollect"] forState:UIControlStateNormal];
            [self.albumView reloadWithPhotoUrls:self.detailPageModel.photoArray];
            [self.goodList reloadData];
        }
    }];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        GRGoodDetailContentCell * contentCell = [tableView dequeueReusableCellWithIdentifier:@"contentCell" forIndexPath:indexPath];
        contentCell.detailModel = self.detailPageModel;
        return contentCell;
    }else if (indexPath.section == 1){
        GRDetailPageStoreCelll * userStoreCell = [tableView dequeueReusableCellWithIdentifier:@"storeCell" forIndexPath:indexPath];
        userStoreCell.msgModel =self.detailPageModel.applyStore[indexPath.row];
        return userStoreCell;
    }else if (indexPath.section == 2){
        GRGoodCountTableViewCell * countCell = [tableView dequeueReusableCellWithIdentifier:@"countCell" forIndexPath:indexPath];
        countCell.countModel = self.detailPageModel.goodArr[indexPath.row];
        return countCell;
    }else if (indexPath.section == 3){
        GRGoodWebHtmlCell * webCell = [tableView dequeueReusableCellWithIdentifier:@"webCell" forIndexPath:indexPath];
        webCell.intro = self.detailPageModel.intro;
        webCell.delegate = self;
        return webCell;
      //网页
    }else if (indexPath.section == 4){
    GRBuyMsgTableViewCell * buyMsgCell = [tableView dequeueReusableCellWithIdentifier:@"BuyMsgCell" forIndexPath:indexPath];
    buyMsgCell.ruleModel = self.detailPageModel.buyNotice[indexPath.row];
    
    return buyMsgCell;
    }else{
        GRSotreCommentTableViewCell * commentCell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
        commentCell.commentModel = self.detailPageModel.commentList[indexPath.row];
        return commentCell;
    }
    
}



-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }else{
        GRStoreSectionHeaderView * headerView =  [ GRStoreSectionHeaderView xx_instantiateFromNib];
        if (section == 1) {
            headerView.titleLabel.text = @"适用商户";
        }else if (section ==2){
            headerView.titleLabel.text = @"商品详情"; //图片详情
        }else if(section == 3){
             headerView.titleLabel.text = @"图片详情";
        }else if(section == 4){
             headerView.titleLabel.text = @"购买须知";
        }else{
            headerView.isComment = YES;
            headerView.titleLabel.text = @"用户评价";
            headerView.commentNumLabel.text = [NSString stringWithFormat:@"(%ld）",(long)self.detailPageModel.commentNum];
            headerView.percentLabel.text = [NSString stringWithFormat:@"%ld%%好评率",(long)self.detailPageModel.commentRate];
        }
        return headerView;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.000000001;
    }else{
        return 45;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 2 ||section == 5) {
        if (section == 2) {
            GRDetailFootSectionView * footView = [GRDetailFootSectionView  xx_instantiateFromNib];
            
            footView.discoutLabel.text = [NSString stringWithFormat:@"优惠价：%.2lf元",self.detailPageModel.discountPrice];
            
            footView.totalLabel.text = [NSString stringWithFormat:@"总价值：%.2lf元",self.detailPageModel.totalPrice];
            return footView;
        }else{
            GRStoreSectionFooterView * footView = [GRStoreSectionFooterView xx_instantiateFromNib];
            footView.delegate = self;
            return footView;
        }
    }else{
        return nil;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 ) {
        return 1;
    }else if (section == 1){
        return self.detailPageModel.applyStore.count;
        
    }else if (section == 2){
        return self.detailPageModel.goodArr.count;
    }else if (section == 3){
        return 1;
        
    } else if (section == 4){
        return self.detailPageModel.buyNotice.count;
    }else{
        return self.detailPageModel.commentList.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 ) {
        return [self.detailPageModel ContentCellHeight];
    }else if (indexPath.section == 1){
        return 85;
        
    }else if (indexPath.section == 2){
        return 28;
    }else if (indexPath.section == 3){
        return webHeight;
        
    }else if (indexPath.section == 4){
        return [GRBuyMsgTableViewCell getCellHeightWithModel:self.detailPageModel.buyNotice[indexPath.row]];
    }else{
        GRStoreCommentModel * commentModel = self.detailPageModel.commentList[indexPath.row];
        return [commentModel cellHeight];
    }
}

- (void)reloadWebViewHeight:(CGFloat)height{
    if (webHeight!=height) {
        webHeight = height;
    [self.goodList reloadData];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        GRGoodDetailMsgModel  * model = self.detailPageModel.applyStore[indexPath.row];
        GRStoreViewController * storeVC = [[GRStoreViewController alloc]init];
        storeVC.storeId = model.id;
        [self.navigationController pushViewController:storeVC animated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section ==2||section == 5 ) {
        if (section == 2) {
            return 55;
        }else{
        return 45;
        }
    }else{
        return 10;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 6;
}

- (IBAction)buyAction:(id)sender {
    if (_isBargain) {
        if (self.detailPageModel.status) {
            GRBarginViewController *bargainVC = [[GRBarginViewController alloc]init];
            bargainVC.barginId = self.detailPageModel.haggleId;
            [self.navigationController pushViewController:bargainVC animated:YES];
        }else{
        NSString * url = [NSString stringWithFormat:@"%@haggle/launchHaggle",GRDeliveryAPI];
        NSDictionary * dic = @{
                               @"discountId":@(self.goodId)
                               };
        [RequestManager MembershipRequestWithURLString:url Method:GR_POST Paramers:dic completionHandler:^(BOOL success, id responseObject, GRError *error) {
            if (success) {
                NSLog(@"%@",responseObject);
                GRhaggleModel *model = [GRhaggleModel yy_modelWithDictionary:responseObject];
                GRBarginViewController *bargainVC = [[GRBarginViewController alloc]init];
                bargainVC.barginId = model.id;
                bargainVC.isShowBarginView = YES;
                bargainVC.currPrice =  [responseObject[@"currPrice"] floatValue];
                [self.navigationController pushViewController:bargainVC animated:YES];
            }else{
                [GRHUD showErrorMsg:error.errorMsg];
            }
        }];
        }
    }else{
   
    GRSubmitOrderVC * submitVC = [[GRSubmitOrderVC alloc]init];
    submitVC.goodId = self.goodId;
    [self.navigationController pushViewController:submitVC animated:YES];
    }
    
    
}

-(void)lookMoreAction:(NSInteger)section{
      GRShowMoreListVC * moreListVC = [[GRShowMoreListVC alloc]init];
    moreListVC.listType = ShowMoreListTypeComment;
    moreListVC.listId = self.goodId;
    [self.navigationController pushViewController:moreListVC animated:YES];
    
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)collectionAction:(UIButton *)button {
    [GRHUD showProgress:@"正在收藏"];
    [GRStoreAction addFavorite:self.detailPageModel.id FavoriteType:@"good" ComplectionHander:^(BOOL success, id responseObject, GRError *error) {
        [GRHUD dismissHUD];
        if (success) {
            if ([responseObject boolValue]) {
                [button  setImage:[UIImage imageNamed:@"alreadyCollect"] forState:UIControlStateNormal];
                   [GRHUD showMessage:@"收藏成功"];
            }else{
                   [GRHUD showMessage:@"取消收藏"];
               [button  setImage:[UIImage imageNamed:@"notCollect"] forState:UIControlStateNormal];
            }
        }else{
            [GRHUD showMessage:@"收藏失败"];
        }
    }];
}

- (IBAction)shareAction:(id)sender {
      [[GRUMengCommon shareUMeng] sharePlatform:self title:self.detailPageModel.title content:self.detailPageModel.content image:self.detailPageModel.shareImage webURL:nil miniApp:YES option:@{@"webpageUrl":(self.detailPageModel.shareUrl?self.detailPageModel.shareUrl:@""),@"userName":(self.detailPageModel.originalId?self.detailPageModel.originalId:@""),@"path":(self.detailPageModel.appGoodsPage?self.detailPageModel.appGoodsPage:@""),@"poster":self.detailPageModel.shareImage}];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
